using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Data;
using System.Web;
using System.Xml;
using System.Xml.XPath;

using Actions;
using Actions.Databases;
using Actions.Connectors;
using Actions.Security;
using Actions.Usecases;

namespace Actions.MetaBase
{
	public class Collection
	{
		private string _databaseId = "";
		private string _id = "0";
	
		private string _name = "";
		private string _title = "";
		private string _dbid = "";
				
		private Properties _properties;
		
		private ElementsPool _ep; 
		private ViewsPool _vp;
				
		private bool _valid = false;
			
		public Collection(string did, string id)
		{
			_databaseId = did;
			_id = id;
			
			QueryResult qr = Manager.i.db(_databaseId).
				query("SELECT * FROM _collections WHERE id='" + _id + "'");
			
			if(qr.res.Count == 1) {
				_name = qr.got(0, "name");
				_title = qr.got(0, "title");
				_dbid = qr.got(0, "dbid");
				
				_properties = new Properties(qr.got(0, "properties"));
		
				_ep = new ElementsPool(_id);
				_ep.init();
				
				_vp = new ViewsPool(_id);
				_vp.init();
				
				_valid = true;
			}						
		}

		public Collection(string did, string name, string title, string dbid, 
			string properties)
		{
			_databaseId = did;
			_name = name;
			_title = title;
			_dbid = dbid;
			_properties = new Properties(Properties.transform(properties));
			
			_valid = false; 
		}

		public string create() 
		{
			if(!_valid) {
				// create table
				
				// create record	
				Manager.i.db(_databaseId).vQuery("INSERT INTO _collections SET name='" + 
					_name + "', title='" + _title + "', dbid='" +
					_dbid  + "', properties='" + _properties.toSQL() + "'");					
				int id = Manager.i.db(_databaseId).lastId(); 
				
				if(id > 0) {	
					_id = Convert.ToString(id);
					_valid = true;	
				
					_ep = new ElementsPool(_id);
					_ep.create(_properties);
					_ep.init();
				
					_vp = new ViewsPool(_id);
					_vp.create(_properties);
					_vp.init();				
				}
			}			
						
			return "";
		}		
		
		public string show()
		{
			string s = "<collection id='" + _id + "'>";
			if(_valid) {
				s += "<name>" + _name + "</name>";
				s += "<title>" + _title + "</title>";
				s += "<dbid>" + _dbid + "</dbid>";
				s += "<properties>" + _properties.toXML() + "</properties>";
				
				// TODO: code 4 elements & views				
			}			
			return s + "</collection>";
		}
		
		public void commit(ref IConnector c)
		{
		
		}

		public void delete()
		{}
										
	}
}